<template>
  <div v-if="!isLoading" id="schedule-info">
    <Calendar
      v-model:value="calendarValue"
      :fullscreen="false"
      @panel-change="onPanelChange"
      @select="onPanelSelect"
    >
      <template #dateCellRender="{ current }">
        <Badge v-if="getDateScheduleCount(current) > 0" status="error" />
      </template>
    </Calendar>
    <Card :bordered="false" class="add-schedule-card">
      <Tag color="processing" class="add-schedule" @click="addSchedule">
        <template #icon>
          <PlusCircleOutlined />
        </template>
        新增日程
      </Tag>
      <!-- <div class="add-schedule" @click="addSchedule"><PlusCircleOutlined /> 新增日程</div> -->
    </Card>

    <Card title="日程信息" class="!my-4 enter-y">
      <Timeline>
        <TimelineItem>
          <template #dot><ClockCircleOutlined style="font-size: 16px" /></template
          ><p style="margin-bottom: 0em"
            ><strong>{{ calendarValue.format('YYYY-MM-DD') }}</strong></p
          >
        </TimelineItem>
        <TimelineItem
          color="#00CCFF"
          v-if="
            !calendarScheduleData ||
            !calendarScheduleData.schedule ||
            calendarScheduleData.schedule.length <= 0
          "
        >
          <p>暂无日程信息</p>
        </TimelineItem>
        <TimelineItem
          :color="getTimelineItemColor(calendarScheduleData.date, item.startTime, item.endTime)"
          :key="s"
          v-for="(item, s) in calendarScheduleData.schedule"
        >
          <Collapse
            v-model:activeKey="activeKey"
            :bordered="false"
            style="background: rgb(255, 255, 255)"
          >
            <template #expandIcon="{ isActive }">
              <CaretRightOutlined :rotate="isActive ? 90 : 0" />
            </template>
            <CollapsePanel
              :key="s"
              style="
                background: #f7f7f7;
                border-radius: 4px;
                margin-bottom: 0px;
                border: 0;
                overflow: hidden;
              "
            >
              <template #header>
                <template v-if="item.level">
                  <Tag v-if="item.level == 1" color="success">一般</Tag>
                  <Tag v-else-if="item.level == 2" color="warning">关键</Tag>
                  <Tag v-if="item.level == 3" color="error">重要</Tag>
                </template>
                <span v-if="item.startTime && item.endTime">
                  <span
                    ><strong>{{ item.startTime }}~{{ item.endTime }}：</strong></span
                  >
                </span>
                <span v-else-if="item.startTime">
                  <span
                    ><strong>{{ item.startTime }}：</strong></span
                  >
                </span>
                <span v-else-if="item.endTime">
                  <span
                    ><strong>{{ item.endTime }}：</strong></span
                  >
                </span>
                <span>{{ item.title }}</span>
              </template>
              <p style="margin-bottom: 0em; margin-left: 1em" v-if="item.address"
                ><strong>地点：</strong>{{ item.address }}</p
              >
              <p style="margin-bottom: 0em; margin-left: 1em" v-if="item.content"
                ><strong>详情：</strong>{{ item.content }}</p
              >
            </CollapsePanel>
          </Collapse>
        </TimelineItem>
        <TimelineItem>
          <template #dot><CheckCircleOutlined style="font-size: 16px" /></template>
        </TimelineItem>
      </Timeline>
    </Card>

    <ScheduleDrawer @register="registerDrawer" />
  </div>
</template>

<script setup name="schedule">
  import { onMounted, onBeforeUnmount, ref } from 'vue';
  import {
    Calendar,
    Badge,
    Card,
    Tag,
    Timeline,
    TimelineItem,
    Collapse,
    CollapsePanel,
  } from 'ant-design-vue';
  import {
    PlusCircleOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    CaretRightOutlined,
  } from '@ant-design/icons-vue';
  import ScheduleDrawer from './ScheduleDrawer.vue';
  import { useDrawer } from '@/components/Drawer';
  import { getUserDayScheduleList, getUserMonthScheduleCount } from '@/api/home';
  import dayjs from 'dayjs';
  import weekday from 'dayjs/plugin/weekday';
  import localeData from 'dayjs/plugin/localeData';
  import { formatToDateTime } from '@/utils/dateUtil';

  dayjs.extend(weekday);
  dayjs.extend(localeData);
  const activeKey = ref([]);
  const calendarValue = ref(dayjs());
  const calendarScheduleCount = ref({});
  const calendarScheduleData = ref([]);
  const [registerDrawer, { openDrawer }] = useDrawer();
  // 添加一个加载状态
  const isLoading = ref(true);
  const currentTime = ref(formatToDateTime(new Date()));
  // 运行定时器，一秒获取一次
  const interval = window.setInterval(
    () => {
      currentTime.value = formatToDateTime(new Date());
      // 每5分钟刷新一次
    },
    1000 * 60 * 5,
  );

  onMounted(async () => {
    // 进来后执行查询
    try {
      const current = calendarValue.value;
      if (current) {
        const year = current.format('YYYY');
        const month = current.format('MM');
        await getMonthScheduleCount(year, month);
        // 数据加载完毕，允许渲染
        isLoading.value = false;
      }
      getDayScheduleListData(current);
    } catch (error) {
      // 处理错误情况
    }
  });
  // 这个界面不在我们视线中的时候，关闭定时器
  onBeforeUnmount(() => {
    window.clearInterval(interval);
  });

  const getTimelineItemColor = (scheduleDate, startTime, endTime) => {
    let color = '';
    if (scheduleDate) {
      if (startTime && endTime) {
        const times = scheduleDate + ' ' + startTime;
        const timee = scheduleDate + ' ' + endTime;
        if (currentTime.value >= times && currentTime.value <= timee) {
          color = 'red';
        } else if (currentTime.value < times) {
          color = 'gray';
        } else if (currentTime.value > timee) {
          color = 'green';
        }
      } else if (endTime) {
        const time = scheduleDate + ' ' + endTime;
        if (currentTime.value > time) {
          color = 'green';
        } else if (currentTime.value < time) {
          color = 'gray';
        } else {
          color = 'red';
        }
      } else if (startTime) {
        const time = scheduleDate + ' ' + startTime;
        if (currentTime.value > time) {
          color = 'green';
        } else if (currentTime.value < time) {
          color = 'gray';
        } else {
          color = 'red';
        }
      }
    }
    return color;
  };

  const getMonthScheduleCount = (year, month) => {
    // 调用接口太慢，需要从缓存中获取
    getUserMonthScheduleCount(year, month).then((data) => {
      calendarScheduleCount.value = data;
    });
  };

  // 点击某一天
  const onPanelSelect = (current) => {
    calendarValue.value = current;
    getDayScheduleListData(current);
  };

  // 日期面板变化
  const onPanelChange = (current) => {
    if (current) {
      const year = current.format('YYYY');
      const month = current.format('MM');
      getMonthScheduleCount(year, month);
    }
  };

  const getDayScheduleListData = (current) => {
    // 查询日期的日程
    const date = current.format('YYYY-MM-DD');
    getUserDayScheduleList(date).then((data) => {
      if (date.indexOf('-2') > 0) {
        calendarScheduleData.value = {
          date,
          schedule: [
            {
              title: '日程标题信息日程标题信息日程标题信息',
              startTime: '10:00',
              endTime: '',
              content:
                '日程内容1日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              level: 0,
              address: '广东省深圳市南山区',
            },
            {
              title: '日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              startTime: '14:00',
              endTime: '15:00',
              content:
                '日程内容1日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              level: 1,
              address: '广东省深圳市南山区',
            },
            {
              title: '日程标题信息日程标题信息日程标题信息',
              startTime: '16:00',
              endTime: '17:27',
              content:
                '日程内容1日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              level: 2,
              address: '广东省深圳市南山区',
            },
            {
              title: '日程标题信息日程标题信息日程标题信息',
              startTime: '',
              endTime: '18:00',
              content:
                '日程内容1日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              level: 3,
              address: '广东省深圳市南山区',
            },
            {
              title: '日程标题信息日程标题信息日程标题信息',
              startTime: '19:00',
              endTime: '21:00',
              content:
                '日程内容1日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息日程标题信息',
              level: 4,
              address: '广东省深圳市南山区',
            },
          ],
        };
      } else {
        calendarScheduleData.value = null;
      }
    });
  };

  const getDateScheduleCount = (current) => {
    let count;
    if (current) {
      const year = current.format('YYYY');
      const month = current.format('MM');
      const day = current.format('DD');
      if (
        Number(year) == calendarScheduleCount.value.year &&
        Number(month) == calendarScheduleCount.value.month
      ) {
        if (
          Number(day) > 0 &&
          calendarScheduleCount.value.dayCount &&
          calendarScheduleCount.value.dayCount.length >= day
        ) {
          count = calendarScheduleCount.value.dayCount[Number(day) - 1];
        }
      }
    }

    return count || 0;
  };

  // 新增日程
  const addSchedule = () => {
    openDrawer(true, { calendarDate: calendarValue.value.format('YYYY-MM-DD'), update: false });
  };
</script>

<style scoped>
  .add-schedule {
    cursor: pointer;
  }
</style>
<style>
  #schedule-info .add-schedule-card .ant-card-body {
    padding: 10px 24px !important;
  }
  #schedule-info .ant-picker-calendar .ant-picker-calendar-header {
    padding: 16px 0;
  }
  #schedule-info .ant-picker-calendar-date-content .ant-badge {
    position: absolute;
    z-index: 2;
    margin: 2px 0 0 9px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  #schedule-info .ant-tag {
    margin-inline-end: 2px;
  }
  #schedule-info .ant-timeline .ant-timeline-item {
    padding-bottom: 10px;
  }
  #schedule-info .ant-collapse > .ant-collapse-item > .ant-collapse-header {
    padding: 5px 10px;
  }
  #schedule-info .ant-collapse .ant-collapse-content > .ant-collapse-content-box {
    padding: 0px 5px 10px 5px;
  }
</style>
